<template src="./template.html"></template>

<script>
/* global _, moment */
import ResizeMixin from 'mixins/resize'
import { PAGE_CONFIG } from 'common/consts'
import { COL_INDEXS } from './consts'
import { getEmployeeEmpPart, getCourseNoGroupUser, getCourseUserLabels, addCourseUser, setCourseGroupUser, getCourseStuGroup } from '../models'

export default {
  mixins: [ResizeMixin],
  props: {
    dialogVisible: {
      type: Boolean,
      required: true
    },
    courseId: {
      type: String,
      default: ''
    },
    isGroup: {
      type: Boolean,
      default: false
    },
    groupId: {
      type: String,
      default: ''
    },
    title: {
      type: String,
      default: '添加学员'
    }
  },
  data() {
    return {
      isLoading: false,
      COL_INDEXS,
      groupList: [],
      userLabels: [],

      tableList: [],
      PAGE_CONFIG: PAGE_CONFIG,
      pageNo: PAGE_CONFIG.defaultPageNo,
      pageSize: PAGE_CONFIG.defaultPageSize,
      totalCount: 0,
      filterForm: {
        q: '',
        userLable: ''
      },

      groupId: '',
      selectStuData: [],
      isCheckAll: false,

      debounceSave: null
    }
  },
  watch: {
    dialogVisible(val) {
      this.$emit('update:dialogVisible', val)
      this.$set(this.filterForm, 'q', '')
      if (!this.isGroup) {
        this.groupId = ''
      }
      this.isCheckAll = false
      this.selectStuData = []
      if (val) {
        this.$search()
        this.$getCourseStuGroup()
      }
    },
    isGroup() {
      if (this.isGroup) {
        this.COL_INDEXS.push({
          prop: 'nickName',
          label: '加入课程时间'
        })
      }
    }
  },
  methods: {
    // 自定义多选框全选
    $handleChangeCheckAll(val) {
      for (let i = 0; i < this.tableList.length; i += 1) {
        this.$set(this.tableList[i], 'checked', val)
        console.log(this.selectStuData, this.tableList)
        const index = this.selectStuData.findIndex(item => (this.tableList[i].userId || this.tableList[i].id) === (item.userId || item.id))
        if (index === -1 && val) {
          this.selectStuData.push(this.tableList[i])
        } else if (index > -1 && !val) {
          this.selectStuData.splice(index, 1)
        }
      }
    },
    // 自定义多选框单选
    $handleChangeChecked(index) {
      this.isCheckAll = false
      const index1 = this.selectStuData.findIndex(item => (this.tableList[index].userId || this.tableList[index].id) === (item.userId || item.id))
      if (index1 === -1 && this.tableList[index].checked) {
        this.selectStuData.push(this.tableList[index])
      } else if (index1 > -1) {
        this.selectStuData.splice(index1, 1)
      }

      if (this.tableList[index].checked) {
        const isCheckAllArr = this.tableList.filter(item => item.checked)
        if (isCheckAllArr.length === this.tableList.length) {
          this.isCheckAll = true
        }
      }
    },
    $search() {
      this.pageNo = 1
      this.$getTableList()
    },
    async $getTableList() {
      this.isLoading = true;
      const params = {
        ...this.filterForm,
        courseId: this.courseId,
        limit: this.pageSize,
        page: this.pageNo,
        orderType: 'desc'
      };

      let func = getEmployeeEmpPart
      if (this.isGroup) {
        func = getCourseNoGroupUser
        params.type = 1
      }
      try {
        const { data } = await func(params);
        this.tableList = (data.list || []).map(item => ({
          ...item,
          checked: this.selectStuData.findIndex(sit => (sit.userId || sit.id) === (item.userId || item.id)) > -1,
          createTime: item.createTime && moment(item.createTime).format('YYYY-MM-DD HH:mm'),
          joinTime: item.joinTime && moment(item.joinTime).format('YYYY-MM-DD HH:mm'),
        }))
        this.initCheckAll(this.tableList)
        this.totalCount = data.total
        this.isLoading = false;
      } catch (err) {
        this.isLoading = false;
        this.$message.error(err.message || err.message || '获取列表出错')
      }
    },
    initCheckAll(data) {
      if (data.length <= 0) {
        this.isCheckAll = false
        return
      }
      const curCheckNum = data.filter(it => it.checked).length
      if (curCheckNum < data.length) {
        this.isCheckAll = false
        return
      }
      this.isCheckAll = true
    },
    async $getCourseUserLabels() {
      const params = {
        courseId: this.courseId,
        limit: 99999,
        page: 1,
      };
      try {
        const { data } = await getCourseUserLabels(params);
        this.userLabels = data || []
      } catch (err) {
        this.$message.error(err.message || '获取分组出错')
      }
    },
    async $getCourseStuGroup() {
      const params = {
        courseId: this.courseId,
        limit: 99999,
        page: 1,
      };
      try {
        const { data } = await getCourseStuGroup(params);
        this.groupList = data.list
      } catch (err) {
        this.$message.error(err.message || '获取分组出错')
      }
    },
    $handlePageChange() {
      this.$getTableList();
    },
    $debounceSave() {
      if (!this.debounceSave) {
        this.debounceSave = _.debounce(this.$handleSave, 500)
      }
      this.debounceSave()
    },
    async $handleSave() {
      this.isLoading = true
      const params = {
        groupId: this.groupId,
        courseId: this.courseId,
        // userIds: this.selectStuData.map(it => (it.userId || it.id))
      }

      let func = addCourseUser
      if (this.isGroup) {
        func = setCourseGroupUser
        params.type = 1
        params.userIds = this.selectStuData.map(it => (it.userId || it.id))
      } else {
        params.userIdList = this.selectStuData.map(it => (it.userId || it.id))
      }
      try {
        await func(params)
        this.$message.success('保存成功')
        this.$emit('saveSucc', () => {
          this.isLoading = false
        })
      } catch (err) {
        this.isLoading = false
        this.$message.error(err.message || err.message || '保存信息出错')
      }
    }
  },
  mounted() {
    this.$getCourseUserLabels()
  }
}
</script>
